import { getShopList, getSpecialsPage } from '../../../api/goods.js';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    TitleBarHeight: app.globalData.TitleBarHeight,
    bgTopUrl: 'https://mall-1300452376.cos.ap-guangzhou.myqcloud.com/7b765fb89b673e61e6111443c45c7b43d4298588af955c0985814aea122b91df.jpg',
    categoryList: [{}, {}],
    categoryIndex: 0,
    categoryId: '',
    shopList: [],
    pageInfo: {
      pageNo: 1,
      pageSize: 10,
    },
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.init();
  },
  async init() {
    const res = await getShopList();
    res &&
      res.length &&
      res.unshift({
        id: '0',
        name: '推荐',
      });

    this.setData(
      {
        categoryList: res || [],
        categoryId: '0',
      },
      () => {
        this.getShopInfo(true);
      },
    );
  },
  chooseCategory(e) {
    const { index, id } = e.currentTarget.dataset;
    this.setData(
      {
        categoryIndex: index,
        categoryId: id,
      },
      () => {
        this.getShopInfo(true);
      },
    );
  },
  async getShopInfo(fresh = false) {
    if (fresh) {
      this.data.pageInfo.pageNo = 1;
    }
    const params = {
      ...this.data.pageInfo,
      categoryId: this.data.categoryId,
    };
    const storeInfo = await getSpecialsPage(params);
    storeInfo.activities.list.map((t) => {
      t.saleNums = t.totalStock - t.stock;
      t.marketPrice = t.marketPrice && (t.marketPrice / 100).toFixed(2)
      t.seckillPrice = t.seckillPrice && (t.seckillPrice / 100).toFixed(2)
      t.savePrice = t.marketPrice && t.seckillPrice ? (parseFloat(t.marketPrice) - parseFloat(t.seckillPrice)).toFixed(2) : 0
      return t
    });
    this.setData({
      shopList: fresh ? storeInfo.activities.list : this.data.shopList.concat(storeInfo.activities.list),
    });
  },
  onReachBottom() {
    this.data.pageInfo.pageNo++;
    this.getShopInfo();
  },
  goBack() {
    wx.navigateBack()
  },
  runGoodsDetail(e) {
    const {item} = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/goods/details/index?goodsId=${item.spuId}`,
    });
  }
});
